import {IProduct,Cproduct} from '../types/product';


interface IState{
    list:IProduct[],
    carList:Cproduct[],
    checkAll:boolean,
    total:number
}

let initData:IState = {
    list:[],  //商品列表
    carList:[], //购物车列表
    checkAll:false, //全选input的选中状态
    total:0 //总价格
}

//查找商品是否添加过
function getIndex(data:Cproduct[],id:number){
    return data.findIndex((item:Cproduct) => item.id === id)
}

//总价格

function totalMoney(data:Cproduct[]){
    //选中商品价格总和
    return data.reduce((pre:number,cur:Cproduct) => {
        return pre += cur.checked ? cur.num*cur.price : 0
    },0)
}

export default (state=initData,action:any) => {
    switch (action.type) {
        //初始化数据
        case 'INIT_LIST':
            return {...state,list:[...action.list]}
        case 'ADD_PRO':{
            //添加商品
            //action  target 添加对象
            let target = action.target;
            let index = getIndex(state.carList,target.id);
            if(index != -1){
                //2.不是第一次添加
                state.carList[index].num++;
            }else{
                //1.第一次添加  
                target.num = 1;  //数量
                target.checked = true; //选中
                state.carList.push(target);
            }
            //全选是否要选中
            state.checkAll = state.carList.every((item:Cproduct) => item.checked);
            state.total = totalMoney(state.carList);
            return {...state,carList:[...state.carList]}
        }
        case 'CHANGE_NUM':{
            //id num：数量改变之后
            let index = getIndex(state.carList,action.id); //-1
            //标识 isDel 是否要删除
            if(action.isDel){
                //删掉
                state.carList.splice(index,1);
            }else{
                let target = state.carList[index];
                target.num = action.num;
                state.carList[index] = {...target};
            }
            state.total = totalMoney(state.carList);
            return {...state,carList:[...state.carList]}
        }
        case 'CHANGE_CHECKED':{
            //id checked:修改之后的选中状态
            let index = getIndex(state.carList,action.id);
            let target = state.carList[index];
            target.checked = action.checked;
            state.carList[index] = {...target};
            //全选是否要选中
            state.checkAll = state.carList.every((item:Cproduct) => item.checked);
            state.total = totalMoney(state.carList);
            return {...state,carList:[...state.carList]}
        }

        case 'CHECK_ALL':{
            //全选按钮的选中状态  state.carlist所有的对象的checked有设置为全选按钮的状态
            state.carList = state.carList.map(item => {
                item.checked = action.checkAll;
                return {...item}
            })
            state.checkAll = action.checkAll; //全选按钮
            state.total = totalMoney(state.carList);
            return {...state,carList:[...state.carList]}
        }
        default:
            return state;
    }
}